from googlemaps import GoogleMaps,GoogleMapsError
import os
import time
import logging
import gpolyencode
import json

modStrGmapsApiKey = "AIzaSyADP4in53jxtD-6eJRtIZdj7AW6ofvOo9o"
modGmapsApi = GoogleMaps(modStrGmapsApiKey)
modGPolyEncoder = gpolyencode.GPolyEncoder()
def EncodePolyLine(lstPoints):
  return json.dumps(modGPolyEncoder.encode(lstPoints) )
#return list of gps locations given locations
def GetGPS(lstStrNames):
  lstLocatTuples = []
  for strItemOfLSN in lstStrNames:
        
    result = modGmapsApi.geocode(strItemOfLSN)
    placemark = result['Placemark'][0]
    lng, lat = placemark["Point"]['coordinates'][0:2]
    lstLocatTuples.append( (lat, lng) )
    time.sleep(0.2)
  
  return lstLocatTuples

#given list of locations, return adminstrative area
def GetAdminArea(lstOfLstsTextAndLocats,lstFailLocations):
  #logging.info(len(lstOfLstsTextAndLocats))
  #logging.info(lstOfLstsTextAndLocats)
  strAdminArea = ""
  for itemOfLOLTAL in lstOfLstsTextAndLocats:
    #logging.info(itemOfLOLTAL)  
    if itemOfLOLTAL[1] not in lstFailLocations and itemOfLOLTAL[1]!= None:
      try:
        strAdminArea = modGmapsApi.geocode(itemOfLOLTAL[1])['Placemark'][0]['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName']
  
      except KeyError:
        logging.error("KeyError, Failing Location: " + itemOfLOLTAL[1])
        itemOfLOLTAL[1] = "Dud"
        time.sleep(0.2)  
  
      except  GoogleMapsError:
        
        logging.error("GoogleMapsError, Failing Location: " + itemOfLOLTAL[1])
        itemOfLOLTAL[1] = "Dud"
        time.sleep(0.2)
  
      except UnicodeDecodeError:
        logging.error("UnicodeDecodeError, Failing location: " + itemOfLOLTAL[1])
        itemOfLOLTAL[1] = "Dud"
        time.sleep(0.2)
      
      finally:
        itemOfLOLTAL[1] = strAdminArea
        time.sleep(0.2)
    else:
      itemOfLOLTAL[1] = "Dud"
  #logging.info(lstOfLstsTextAndLocats)
  lstOfLstsTextAndLocats[:] = [itemOfLOLTAL for itemOfLOLTAL in lstOfLstsTextAndLocats if not CheckDuds(itemOfLOLTAL[1])]
  lstOfLstsTextAndLocats.sort(key=lambda tup: tup[1])
  #for item in lstOfLstsTextAndLocats:
    #logging.info(item)  
  return lstOfLstsTextAndLocats
  #logging.info(lstOfLstsTextAndLocats)
  
  
    
      


def CheckDuds(strLocation):
  if strLocation == "Dud":
    return True
  else:
    return False
  
    